// import env from '../env.js'; //引入需要的api
import ajax from "./ajax";
import tools from './tools.js';

function upload(filePath, formData) {
	console.log(filePath, "请求图片参数", formData, '请求附加参数')
	// return;
	return new Promise((resolve, reject) => {
		let num = 0;
		let img_arr = [];
		let arrResult = [];
		let successNum = 0;
		let errNum = 0;
		let token = uni.getStorageSync('userInfo').token;
		filePath.forEach((item, index) => {
			uni.uploadFile({
				url: ajax.apiUrl + '/wxCommon/wxUploadFile', //仅为示例，非真实的接口地址
				filePath: item.tempFilePath || item.path,
				name: 'file_name',
				timeout: 1800000,
				header: {
					"content-type": "multipart/form-data",
					'Authorization': token ? `Bearer ${token}` : '',
				},
				// formData: formData || {
				// 	folder: 'wxFile'
				// },
				complete() {

				},
				success(res) {
					num++;
					try {
						let data = res.data
						data = JSON.parse(tools.decode_h(data))
						// console.log(data, "解密数据")
						// console.log(data)
						if (data.code == '200') {
							img_arr.push({
								data: data.data,
								index: index
							})
							arrResult.push({
								data: data.data,
								index: index
							})
							successNum++;
						} else {
							errNum++;
						}
						// 上传完处理
						if (filePath.length == num) {
							img_arr.forEach(item => {
								arrResult[item.index] = item.data;
							})
							resolve({
								arrResult,
								successNum,
								errNum
							})
						}
					} catch (error) {
						console.log(error, "解密错误")
						uni.showToast({
							title: '解密错误',
							icon: 'error'
						})
					}
				},
				fail(err) {
					console.log(err, '上传报错')
					// 上传完处理
					if (filePath.length == num) {
						img_arr.forEach(item => {
							arrResult[item.index] = item.data;
						})
						resolve({
							arrResult,
							successNum,
							errNum
						})

					}
				}

			})
		})
	})
}
export default upload;